package com.xz.util.openplatform;/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/// <summary

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.TimeZone;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/// 开放平台请求签名
/// </summary>
public class OpenVendorCryptographyUtils {

    /// <summary>
    /// 获取请求加密
    /// </summary>
    /// <param name="enterpriseId"></param>
    /// <param name="enterpriseSecret"></param>
    /// <returns></returns>
    public static OpenVendorAuthModel CreateAuthModel(String vendorId, String secret) {
        OpenVendorAuthModel model = new OpenVendorAuthModel();
        model.VendorId = vendorId;
        model.Random = CreateRandomCode(16);
        model.Timestamp = CreateTimestamp();

        model.Signature = CreateSignature(model, secret);
        return model;
    }

    /// <summary>
    /// 创建签名
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public static String CreateSignature(OpenVendorAuthModel model, String secret) {

        List<String> list = new ArrayList<String>();
        list.add("VendorId=" + model.VendorId);
        list.add("Timestamp=" + model.Timestamp);
        list.add("Secret=" + secret);
        list.add("Random=" + model.Random);

        String auth = String.join("&", list);

        String newSignature = "";

        try {
            newSignature = GetSha256(auth);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(OpenVendorCryptographyUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(OpenVendorCryptographyUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return newSignature;
    }

    /// <summary>
    /// 获取时间戳
    /// </summary>
    /// <returns></returns>
    public static String CreateTimestamp() {
        //先获取UTC时间,再格式化
      return Long.toString( DateTimeUtils.GetUnixTimeStamp());
    }

    /// <summary>
    /// 获取随机数
    /// </summary>
    /// <param name="codeLen"></param>
    /// <returns></returns>
    public static String CreateRandomCode(int codeLen) {
        String codeSerial = "2,3,4,5,6,7,a,c,d,e,f,h,i,j,k,m,n,p,r,s,t,A,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,U,V,W,X,Y,Z";
        if (codeLen == 0) {
            codeLen = 16;
        }
        String[] arr = codeSerial.split(",");
        String code = "";
        int randValue = -1;
        Random rand = new Random();
        for (int i = 0; i < codeLen; i++) {
            randValue = rand.nextInt(arr.length - 1);
            code += arr[randValue];
        }
        return code;
    }

    public static String GetSha256(String value) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest messageDigest;
        String encodeStr = "";

        messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(value.getBytes("UTF-8"));
        encodeStr = byte2Hex(messageDigest.digest());
        return encodeStr;
    }

    /**
     * 将byte转为16进制
     *
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes) {

        StringBuffer stringBuffer = new StringBuffer();

        String temp = null;

        for (int i = 0; i < bytes.length; i++) {

            temp = Integer.toHexString(bytes[i] & 0xFF);

            if (temp.length() == 1) {
                //1得到一位的进行补0操作

                stringBuffer.append("0");

            }

            stringBuffer.append(temp);

        }

        return stringBuffer.toString();

    }

}
